package cn.minds.capture.dispatch.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import cn.minds.capture.dispatch.CaputureInputStream;
import cn.minds.capture.dispatch.CaputureOutputStream;
import cn.minds.capture.dispatch.Connect;
import cn.minds.capture.dispatch.Protocol;
import cn.minds.capture.dispatch.TaskManager;

public class Client extends Connect {

	private String host;
	private int port;
	private int timeout = Protocol.DEFAULT_TIMEOUT;

	public Client(TaskManager taskManager, String host, int port) {
		this.host = host;
		this.port = port;
		setTaskManager(taskManager);
		taskManager.setConnect(this);
	}

	public boolean connect() {
		if (!isConnected()) {
			try {
				Socket socket = new Socket();
				socket.setReuseAddress(true);
				socket.setKeepAlive(true);
				socket.setTcpNoDelay(true);
				socket.setSoLinger(true, 0);
				socket.connect(new InetSocketAddress(host, port), timeout);
				setOutputStream(new CaputureOutputStream(socket.getOutputStream()));
				setInputStream(new CaputureInputStream(socket.getInputStream()));
				readCommand();
			} catch (IOException ex) {
				disConnect();
				return false;
			}
			return true;
		}
		return false;
	}
}
